<template>
  <div class="document-manage-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">文档管理</h1>
        <p class="page-subtitle">管理常用表单和规范性文件</p>
      </div>
      <div class="header-actions">
        <el-button size="large" type="primary" @click="openUploadDialog">
          <el-icon><Upload /></el-icon> 上传文档
        </el-button>
        <el-button size="large" @click="refreshDocuments">
          <el-icon><Refresh /></el-icon> 刷新
        </el-button>
      </div>
    </div>

    <!-- 文档分类导航 -->
    <div class="category-navigation">
      <h3 class="category-title">文档分类</h3>
      <div class="category-grid">
        <div 
          v-for="category in documentCategories" 
          :key="category.value"
          class="category-card"
          @click="navigateToCategory(category.value)"
        >
          <div class="category-icon">
            <el-icon>
              <component :is="category.icon" />
            </el-icon>
          </div>
          <div class="category-info">
            <h4 class="category-name">{{ category.label }}</h4>
            <p class="category-desc">{{ category.description }}</p>
            <div class="category-count">
              <span>{{ getCategoryCount(category.value) }} 个文档</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 文档分类和搜索 -->
    <div class="filter-section">
      <div class="filter-left">
        <el-select v-model="selectedCategory" placeholder="选择分类" clearable @change="filterDocuments">
          <el-option label="全部" value="" />
          <el-option label="表单模板" value="form-template" />
          <el-option label="国家标准" value="national-standard" />
          <el-option label="企业标准" value="enterprise-standard" />
          <el-option label="规范性文件" value="regulatory-document" />
          <el-option label="技术文档" value="technical-document" />
          <el-option label="操作手册" value="operation-manual" />
          <el-option label="三方报告" value="third-party-report" />
          <el-option label="其他" value="other" />
        </el-select>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索文档名称或描述"
          clearable
          @input="filterDocuments"
          style="width: 300px; margin-left: 16px;"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <div class="filter-right">
                 <el-radio-group v-model="viewMode" @change="filterDocuments">
           <el-radio-button value="grid">网格视图</el-radio-button>
           <el-radio-button value="list">列表视图</el-radio-button>
         </el-radio-group>
      </div>
    </div>

    <!-- 文档展示区域 -->
    <div class="main-content">
      <div class="panel-card">
        <!-- 网格视图 -->
        <div v-if="viewMode === 'grid'" class="document-grid">
          <div
            v-for="doc in filteredDocuments"
            :key="doc.id"
            class="document-card"
                         @click="handlePreviewDocument(doc)"
          >
            <div class="document-icon">
              <el-icon>
                <component :is="getFileIcon(doc.fileType)" />
              </el-icon>
            </div>
            <div class="document-info">
              <h3 class="document-title">{{ doc.name }}</h3>
              <p class="document-desc">{{ doc.description }}</p>
                             <div class="document-meta">
                 <span class="document-category">{{ getCategoryLabel(doc.category) }}</span>
                 <span class="document-size">{{ doc.fileType === 'link' ? '链接' : formatFileSize(doc.fileSize) }}</span>
               </div>
              <div class="document-actions">
                <el-button size="small" type="primary" @click.stop="downloadDocument(doc)">
                  <el-icon><Download /></el-icon> 下载
                </el-button>
                <el-button size="small" @click.stop="copyLink(doc)">
                  <el-icon><Link /></el-icon> 复制链接
                </el-button>
                <el-button 
                  v-if="userRole === 'admin' || userRole === 'superadmin'" 
                  size="small" 
                  type="danger" 
                  @click.stop="deleteDocument(doc)"
                >
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 列表视图 -->
        <div v-else class="document-list">
          <el-table :data="filteredDocuments" style="width: 100%">
            <el-table-column prop="name" label="文档名称" min-width="220">
              <template #default="{ row }">
                                 <div class="document-name-cell">
                   <el-icon style="margin-right: 8px; color: #409eff;">
                     <component :is="getFileIcon(row.fileType)" />
                   </el-icon>
                   <span>{{ row.name }}</span>
                 </div>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" min-width="220" />
            <el-table-column prop="category" label="分类" width="120">
              <template #default="{ row }">
                <el-tag v-if="getCategoryTagType(row.category)" :type="getCategoryTagType(row.category)">
                  {{ getCategoryLabel(row.category) }}
                </el-tag>
                <el-tag v-else>
                  {{ getCategoryLabel(row.category) }}
                </el-tag>
              </template>
            </el-table-column>
                         <el-table-column prop="fileSize" label="大小" width="120">
               <template #default="{ row }">
                 {{ row.fileType === 'link' ? '链接' : formatFileSize(row.fileSize) }}
               </template>
             </el-table-column>
            <el-table-column prop="uploadTime" label="上传时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.uploadTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="250" fixed="right">
              <template #default="{ row }">
                                 <div style="display: flex; gap: 8px; flex-wrap: nowrap;">
                   <el-button size="small" type="primary" @click="handlePreviewDocument(row)">
                     <el-icon><View /></el-icon> 预览
                   </el-button>
                   <el-button size="small" @click="downloadDocument(row)">
                     <el-icon><Download /></el-icon> 下载
                   </el-button>
                   <el-button 
                     v-if="userRole === 'admin' || userRole === 'superadmin'" 
                     size="small" 
                     type="danger" 
                     @click="deleteDocument(row)"
                   >
                     <el-icon><Delete /></el-icon> 删除
                   </el-button>
                 </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 空状态 -->
        <div v-if="filteredDocuments.length === 0" class="empty-state">
          <div class="empty-icon">📄</div>
          <p class="empty-text">暂无文档</p>
          <el-button type="primary" @click="openUploadDialog">上传第一个文档</el-button>
        </div>
      </div>
    </div>

    <!-- 上传文档对话框 -->
    <el-dialog
      v-model="showUploadDialog"
      title="上传文档"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="uploadForm" :rules="uploadRules" ref="uploadFormRef" label-width="100px">
        <el-form-item label="文档名称" prop="name">
          <el-input v-model="uploadForm.name" placeholder="请输入文档名称" />
        </el-form-item>
        <el-form-item label="文档描述" prop="description">
          <el-input
            v-model="uploadForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入文档描述"
          />
        </el-form-item>
        <el-form-item label="文档分类" prop="category">
          <el-select v-model="uploadForm.category" placeholder="选择分类">
            <el-option label="表单模板" value="form-template" />
            <el-option label="国家标准" value="national-standard" />
            <el-option label="企业标准" value="enterprise-standard" />
            <el-option label="规范性文件" value="regulatory-document" />
            <el-option label="技术文档" value="technical-document" />
            <el-option label="操作手册" value="operation-manual" />
            <el-option label="三方报告" value="third-party-report" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
                 <el-form-item label="上传文件" prop="file">
           <div class="upload-section">
             <el-upload
               ref="uploadRef"
               :auto-upload="false"
               :on-change="handleFileChange"
               :file-list="fileList"
               :limit="1"
               accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.jpg,.jpeg,.png,.gif"
             >
               <template #trigger>
                 <el-button type="primary">选择文件</el-button>
               </template>
               <template #tip>
                 <div class="el-upload__tip">
                   支持 PDF、Word、Excel、PowerPoint、图片等格式，文件大小不超过 50MB
                 </div>
               </template>
             </el-upload>
             <div class="upload-divider">
               <span>或者</span>
             </div>
           </div>
         </el-form-item>
                   <el-form-item label="网盘链接" prop="cloudLink">
            <el-input v-model="uploadForm.cloudLink" placeholder="输入网盘分享链接（如果不上传文件）">
              <template #append>
                <el-button @click="testCloudLink">测试链接</el-button>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item label="提取码" prop="extractCode" v-if="showExtractCode">
            <el-input v-model="uploadForm.extractCode" placeholder="输入提取码（如果有）" style="width: 200px;">
              <template #append>
                <el-button @click="validateExtractCode">验证</el-button>
              </template>
            </el-input>
          </el-form-item>
          
          <div class="form-tip">
            如果不上传本地文件，请提供网盘链接
            <br>
            <small style="color: #67c23a;">💡 推荐：OneDrive、Google Drive（无需登录，支持在线预览）</small>
            <br>
            <small style="color: #e6a23c;">⚠️ 百度网盘需要提取码且不支持在线预览，阿里云盘、夸克网盘需要登录才能预览</small>
          </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
                      <el-button @click="closeUploadDialog">取消</el-button>
          <el-button type="primary" @click="uploadDocument" :loading="uploading">
            {{ uploading ? '上传中...' : '上传' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 文档预览对话框 -->
    <el-dialog
      v-model="showPreviewDialog"
      :title="previewDocument.name"
      width="80%"
      :close-on-click-modal="false"
    >
             <div class="preview-content">
         <!-- PDF 预览 -->
         <iframe
           v-if="previewDocument.fileType === 'pdf'"
           :src="previewDocument.url"
           width="100%"
           height="600px"
           frameborder="0"
         ></iframe>
         
         <!-- 图片预览 -->
         <div v-else-if="isImageFile(previewDocument.fileType)" class="image-preview">
           <img :src="previewDocument.url" alt="文档预览" style="max-width: 100%; height: auto;" />
         </div>
         
         <!-- 网盘链接预览 -->
         <div v-else-if="previewDocument.fileType === 'link'" class="link-preview">
           <div class="preview-icon">
             <el-icon style="font-size: 64px; color: #409eff;">
               <Link />
             </el-icon>
           </div>
                        <div class="link-info">
               <h3>网盘文件</h3>
               <p class="link-url">{{ previewDocument.url }}</p>
               <p v-if="previewDocument.extractCode" class="extract-code">
                 提取码：<span class="code">{{ previewDocument.extractCode }}</span>
                 <el-button size="small" @click="copyExtractCode(previewDocument.extractCode)">
                   <el-icon><Document /></el-icon> 复制
                 </el-button>
               </p>
             
             <!-- 支持预览的网盘 -->
             <div v-if="canPreviewLink(previewDocument.url)" class="preview-options">
               <h4>预览选项</h4>
               <div class="preview-actions">
                 <el-button type="success" @click="previewInIframe(previewDocument.url)">
                   <el-icon><View /></el-icon> 在线预览
                 </el-button>
                 <el-button type="primary" @click="openLink(previewDocument.url)">
                   <el-icon><Link /></el-icon> 打开链接
                 </el-button>
                 <el-button @click="copyLink(previewDocument)">
                   <el-icon><Document /></el-icon> 复制链接
                 </el-button>
               </div>
             </div>
             
             <!-- 不支持预览的网盘 -->
             <div v-else class="link-actions">
               <el-button type="primary" @click="openLink(previewDocument.url)">
                 <el-icon><Link /></el-icon> 打开链接
               </el-button>
               <el-button @click="copyLink(previewDocument)">
                 <el-icon><Document /></el-icon> 复制链接
               </el-button>
             </div>
             
                           <div class="link-tips">
                <p>💡 提示：</p>
                <ul>
                  <li v-if="canPreviewLink(previewDocument.url)">此网盘支持在线预览，点击"在线预览"可直接查看文件</li>
                  <li>点击"打开链接"将在新标签页中打开网盘文件</li>
                  <li>部分网盘支持在线预览，具体取决于网盘服务商</li>
                  <li>如果无法预览，请下载后查看</li>
                  <li v-if="previewDocument.url.includes('pan.baidu.com')">百度网盘：不支持在线预览，请点击"打开链接"查看</li>
                  <li v-if="previewDocument.url.includes('aliyundrive.com')">阿里云盘：需要登录账号才能预览文件</li>
                  <li v-if="previewDocument.url.includes('quark.cn')">夸克网盘：需要登录账号才能预览文件</li>
                  <li v-if="previewDocument.url.includes('onedrive.live.com') || previewDocument.url.includes('1drv.ms')">OneDrive：无需登录即可预览</li>
                  <li v-if="previewDocument.url.includes('drive.google.com')">Google Drive：无需登录即可预览</li>
                </ul>
              </div>
           </div>
         </div>
         
         <!-- 其他文件类型 -->
         <div v-else class="file-preview">
                      <div class="preview-icon">
              <el-icon style="font-size: 64px; color: #409eff;">
                <component :is="getFileIcon(previewDocument.fileType)" />
              </el-icon>
            </div>
           <p class="preview-text">此文件类型不支持在线预览</p>
                      <el-button type="primary" @click="downloadDocument(previewDocument)">
              <el-icon><Download /></el-icon> 下载查看
            </el-button>
         </div>
       </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPreviewDialog = false">关闭</el-button>
                     <el-button type="primary" @click="downloadDocument(previewDocument)">
             <el-icon><Download /></el-icon> 下载
           </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Upload, 
  Refresh, 
  Search, 
  Download, 
  Link, 
  Delete, 
  View, 
  Document, 
  Picture 
} from '@element-plus/icons-vue'
import AV from '../leancloud'

const router = useRouter()

// 响应式数据
const documents = ref([])
const filteredDocuments = ref([])
const selectedCategory = ref('')
const searchKeyword = ref('')
const viewMode = ref('grid')
const showUploadDialog = ref(false)
const showPreviewDialog = ref(false)
const uploading = ref(false)
const previewDocument = ref({})

// 上传表单
const uploadForm = ref({
  name: '',
  description: '',
  category: '',
  file: null,
  cloudLink: '',
  extractCode: ''
})

// 是否显示提取码输入框
const showExtractCode = ref(false)

const fileList = ref([])
const uploadFormRef = ref()
const uploadRef = ref()

// 表单验证规则
const uploadRules = {
  name: [
    { required: true, message: '请输入文档名称', trigger: 'submit' }
  ],
  description: [
    { required: true, message: '请输入文档描述', trigger: 'submit' }
  ],
  category: [
    { required: true, message: '请选择文档分类', trigger: 'change' }
  ],
  file: [
    { 
      validator: (rule, value, callback) => {
        // 只有当两个字段都为空时才报错
        if (!uploadForm.value.file && !uploadForm.value.cloudLink.trim()) {
          callback(new Error('请选择上传文件或提供网盘链接'))
        } else {
          callback()
        }
      }, 
      trigger: 'submit' 
    }
  ],
  cloudLink: [
    { 
      validator: (rule, value, callback) => {
        // 只有当两个字段都为空时才报错
        if (!uploadForm.value.file && !uploadForm.value.cloudLink.trim()) {
          callback(new Error('请选择上传文件或提供网盘链接'))
        } else {
          callback()
        }
      }, 
      trigger: 'submit' 
    }
  ]
}

// 用户角色（从localStorage获取）
const userRole = ref(localStorage.getItem('userRole') || 'user')

// 文档分类定义
const documentCategories = ref([
  {
    value: 'form-template',
    label: '表单模板',
    description: '检验报告、质量记录等表单模板',
    icon: 'Document'
  },
  {
    value: 'national-standard',
    label: '国家标准',
    description: '行业标准、技术规范等国家标准文件',
    icon: 'Document'
  },
  {
    value: 'enterprise-standard',
    label: '企业标准',
    description: '工艺标准、操作规程等企业内部标准',
    icon: 'Document'
  },
  {
    value: 'regulatory-document',
    label: '规范性文件',
    description: '管理制度、工作流程等规范性文件',
    icon: 'Document'
  },
  {
    value: 'technical-document',
    label: '技术文档',
    description: '技术规范、设计文档等技术文档',
    icon: 'Document'
  },
  {
    value: 'operation-manual',
    label: '操作手册',
    description: '设备操作、工艺流程等操作手册',
    icon: 'Document'
  },
  {
    value: 'third-party-report',
    label: '三方报告',
    description: '第三方检测报告、认证文件等',
    icon: 'Document'
  },
  {
    value: 'other',
    label: '其他',
    description: '其他相关文档',
    icon: 'Document'
  }
])

// 获取分类文档数量
function getCategoryCount(category) {
  return documents.value.filter(doc => doc.category === category).length
}

// 导航到分类页面
function navigateToCategory(category) {
  router.push(`/document-manage/${category}`)
}

// 获取文档列表
async function loadDocuments() {
  try {
    const query = new AV.Query('Document')
    query.descending('createdAt')
    const results = await query.find()
    
    documents.value = results.map(doc => ({
      id: doc.id,
      name: doc.get('name'),
      description: doc.get('description'),
      category: doc.get('category') || 'other', // 确保有默认值
      fileType: doc.get('fileType'),
      fileSize: doc.get('fileSize'),
      url: doc.get('url'),
      cloudLink: doc.get('cloudLink'),
      extractCode: doc.get('extractCode') || '',
      uploadTime: doc.createdAt,
      uploader: doc.get('uploader')
    }))
    
    filterDocuments()
  } catch (error) {
    console.error('加载文档失败:', error)
    
    // 如果是表不存在的错误，显示友好提示
    if (error.message && error.message.includes("doesn't exists")) {
      ElMessage.info('文档管理功能已就绪，您可以开始上传第一个文档')
      documents.value = []
      filterDocuments()
    } else {
      ElMessage.error('加载文档失败: ' + error.message)
    }
  }
}

// 过滤文档
function filterDocuments() {
  let filtered = [...documents.value]
  
  // 按分类过滤
  if (selectedCategory.value) {
    filtered = filtered.filter(doc => doc.category === selectedCategory.value)
  }
  
  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(doc => 
      doc.name.toLowerCase().includes(keyword) ||
      doc.description.toLowerCase().includes(keyword)
    )
  }
  
  filteredDocuments.value = filtered
}

// 文件类型图标
function getFileIcon(fileType) {
  const iconMap = {
    'pdf': 'Document',
    'doc': 'Document',
    'docx': 'Document',
    'xls': 'Document',
    'xlsx': 'Document',
    'ppt': 'Document',
    'pptx': 'Document',
    'txt': 'Document',
    'jpg': 'Picture',
    'jpeg': 'Picture',
    'png': 'Picture',
    'gif': 'Picture',
    'link': 'Link'
  }
  return iconMap[fileType] || 'Document'
}

// 分类标签
function getCategoryLabel(category) {
  const labelMap = {
    'form-template': '表单模板',
    'national-standard': '国家标准',
    'enterprise-standard': '企业标准',
    'regulatory-document': '规范性文件',
    'technical-document': '技术文档',
    'operation-manual': '操作手册',
    'third-party-report': '三方报告',
    'other': '其他'
  }
  return labelMap[category] || '其他'
}

// 分类标签类型
function getCategoryTagType(category) {
  const typeMap = {
    'form-template': 'primary',
    'national-standard': 'success',
    'enterprise-standard': 'warning',
    'regulatory-document': 'info',
    'technical-document': 'danger',
    'operation-manual': 'warning',
    'third-party-report': 'success',
    'other': ''
  }
  return typeMap[category] || ''
}

// 格式化文件大小
function formatFileSize(bytes) {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化日期
function formatDate(date) {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN')
}

// 判断是否为图片文件
function isImageFile(fileType) {
  return ['jpg', 'jpeg', 'png', 'gif'].includes(fileType)
}

// 处理文件选择
function handleFileChange(file) {
  uploadForm.value.file = file.raw
}

// 检测是否为百度网盘链接
function isBaiduPanLink(url) {
  return url.includes('pan.baidu.com')
}

// 测试网盘链接
function testCloudLink() {
  if (!uploadForm.value.cloudLink) {
    ElMessage.warning('请先输入网盘链接')
    return
  }
  
  // 检查是否为百度网盘链接
  if (isBaiduPanLink(uploadForm.value.cloudLink)) {
    showExtractCode.value = true
    ElMessage.info('检测到百度网盘链接，请输入提取码')
  } else {
    showExtractCode.value = false
    ElMessage.success('链接格式正确')
  }
}

// 验证提取码
function validateExtractCode() {
  if (!uploadForm.value.extractCode) {
    ElMessage.warning('请输入提取码')
    return
  }
  
  if (uploadForm.value.extractCode.length < 4) {
    ElMessage.warning('提取码长度不正确')
    return
  }
  
  ElMessage.success('提取码格式正确')
}

// 上传文档
async function uploadDocument() {
  try {
    // 先检查是否提供了文件或网盘链接
    if (!uploadForm.value.file && !uploadForm.value.cloudLink.trim()) {
      ElMessage.error('请选择上传文件或提供网盘链接')
      return
    }
    
    await uploadFormRef.value.validate()
    
    uploading.value = true
    
    let fileUrl = ''
    let fileType = ''
    let fileSize = 0
    
    if (uploadForm.value.file) {
      // 上传文件到 LeanCloud
      const file = new AV.File(uploadForm.value.file.name, uploadForm.value.file)
      await file.save()
      fileUrl = file.url()
      fileType = uploadForm.value.file.name.split('.').pop().toLowerCase()
      fileSize = uploadForm.value.file.size
    } else {
      // 只提供网盘链接的情况
      fileUrl = uploadForm.value.cloudLink
      fileType = 'link' // 标记为链接类型
      fileSize = 0
    }
    
         // 创建文档记录
     const Document = AV.Object.extend('Document')
     const document = new Document()
     
     document.set('name', uploadForm.value.name)
     document.set('description', uploadForm.value.description)
     document.set('category', uploadForm.value.category)
     document.set('fileType', fileType)
     document.set('fileSize', fileSize)
     document.set('url', fileUrl)
     document.set('cloudLink', uploadForm.value.cloudLink || '')
     document.set('extractCode', uploadForm.value.extractCode || '')
     document.set('uploader', localStorage.getItem('currentUsername') || '未知用户')
    
    await document.save()
    
    ElMessage.success(uploadForm.value.file ? '文档上传成功' : '文档链接添加成功')
    closeUploadDialog()
    loadDocuments()
    
  } catch (error) {
    console.error('上传失败:', error)
    
    // 如果是表不存在的错误，提示用户
    if (error.message && error.message.includes("doesn't exists")) {
      ElMessage.error('系统初始化中，请稍后再试')
    } else if (error.message && error.message.includes('请选择上传文件或提供网盘链接')) {
      // 忽略验证错误，因为已经在前面处理了
      return
    } else {
      ElMessage.error('上传失败: ' + error.message)
    }
  } finally {
    uploading.value = false
  }
}

// 打开上传对话框
function openUploadDialog() {
  showUploadDialog.value = true
  // 清除之前的验证状态
  nextTick(() => {
    if (uploadFormRef.value) {
      uploadFormRef.value.clearValidate()
    }
  })
}

// 关闭上传对话框
function closeUploadDialog() {
  showUploadDialog.value = false
  resetUploadForm()
}

// 重置上传表单
function resetUploadForm() {
  uploadForm.value = {
    name: '',
    description: '',
    category: '',
    file: null,
    cloudLink: '',
    extractCode: ''
  }
  showExtractCode.value = false
  fileList.value = []
  
  // 清除表单验证状态
  if (uploadFormRef.value) {
    uploadFormRef.value.resetFields()
    uploadFormRef.value.clearValidate()
  }
  
  // 清除文件上传组件
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 预览文档
function handlePreviewDocument(doc) {
  previewDocument.value = doc
  showPreviewDialog.value = true
}

// 下载文档
function downloadDocument(doc) {
  if (doc.fileType === 'link') {
    // 对于链接类型的文档，直接打开链接
    window.open(doc.url, '_blank')
    ElMessage.success('正在打开链接')
  } else {
    // 对于文件类型的文档，下载文件
    const link = document.createElement('a')
    link.href = doc.url
    link.download = doc.name
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    ElMessage.success('开始下载文档')
  }
}

// 复制链接
function copyLink(doc) {
  let link = doc.cloudLink || doc.url
  
  // 如果是百度网盘且有提取码，一并复制
  if (isBaiduPanLink(link) && doc.extractCode) {
    link += `\n提取码：${doc.extractCode}`
  }
  
  navigator.clipboard.writeText(link).then(() => {
    ElMessage.success('链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 打开链接
function openLink(url) {
  window.open(url, '_blank')
  ElMessage.success('正在打开链接')
}

// 复制提取码
function copyExtractCode(code) {
  navigator.clipboard.writeText(code).then(() => {
    ElMessage.success('提取码已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 检查链接是否支持预览
function canPreviewLink(url) {
  if (!url) return false
  
  // 支持预览的网盘域名
  const previewableDomains = [
    'www.aliyundrive.com',
    'drive.google.com',
    'www.dropbox.com',
    '1drv.ms',
    'onedrive.live.com',
    'wwbq.lanzoub.com', // 蓝奏云
    'wwbq.lanzoux.com', // 蓝奏云备用域名
    'pan.xunlei.com',   // 迅雷云盘
    'cloud.189.cn',     // 天翼云盘
    'pan.quark.cn',     // 夸克网盘
    'share.quark.cn'    // 夸克网盘分享
  ]
  
  try {
    const urlObj = new URL(url)
    return previewableDomains.some(domain => urlObj.hostname.includes(domain))
  } catch {
    return false
  }
}

// 在iframe中预览链接
function previewInIframe(url) {
  // 创建预览对话框
  const previewWindow = window.open('', '_blank', 'width=1200,height=800,scrollbars=yes,resizable=yes')
  
  if (previewWindow) {
    previewWindow.document.write(`
      <!DOCTYPE html>
      <html>
      <head>
        <title>文件预览</title>
        <style>
          body { margin: 0; padding: 0; }
          iframe { width: 100%; height: 100vh; border: none; }
        </style>
      </head>
      <body>
        <iframe src="${url}" allowfullscreen></iframe>
      </body>
      </html>
    `)
    previewWindow.document.close()
    ElMessage.success('正在打开预览窗口')
  } else {
    ElMessage.warning('请允许弹出窗口以进行预览')
    openLink(url)
  }
}

// 删除文档
async function deleteDocument(doc) {
  try {
    await ElMessageBox.confirm(
      `确定要删除文档"${doc.name}"吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    // 删除 LeanCloud 中的记录
    const Document = AV.Object.createWithoutData('Document', doc.id)
    await Document.destroy()
    
    ElMessage.success('文档删除成功')
    loadDocuments()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      
      // 如果是表不存在的错误，提示用户
      if (error.message && error.message.includes("doesn't exists")) {
        ElMessage.error('系统初始化中，请稍后再试')
      } else {
        ElMessage.error('删除失败: ' + error.message)
      }
    }
  }
}

// 刷新文档
function refreshDocuments() {
  loadDocuments()
  ElMessage.success('文档列表已刷新')
}

// 初始化 Document 表（如果不存在）
async function initializeDocumentTable() {
  try {
    // 尝试创建一个测试文档来初始化表
    const Document = AV.Object.extend('Document')
    const testDoc = new Document()
    testDoc.set('name', 'test')
    testDoc.set('description', 'test')
    testDoc.set('category', 'other')
    testDoc.set('fileType', 'txt')
    testDoc.set('fileSize', 0)
         testDoc.set('url', '')
     testDoc.set('cloudLink', '')
     testDoc.set('extractCode', '')
     testDoc.set('uploader', 'system')
    
    await testDoc.save()
    // 立即删除测试文档
    await testDoc.destroy()
    
    console.log('Document 表初始化成功')
  } catch (error) {
    console.log('Document 表已存在或初始化失败:', error.message)
  }
}

// 组件挂载时初始化并加载文档
onMounted(async () => {
  await initializeDocumentTable()
  loadDocuments()
})
</script>

<style scoped>
.document-manage-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
  width: 100%;
}

/* 页面头部 */
.page-header {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  color: white;
  border-radius: 12px;
  padding: 24px 32px;
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.2);
}

.header-content {
  flex: 1;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 分类导航 */
.category-navigation {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.category-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0 0 20px 0;
}

.category-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.category-card {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 12px;
}

.category-card:hover {
  background: #e3f2fd;
  border-color: #409eff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.category-icon {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
  background: #409eff;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.category-icon .el-icon {
  font-size: 24px;
}

.category-info {
  flex: 1;
  min-width: 0;
}

.category-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 4px 0;
  line-height: 1.4;
}

.category-desc {
  font-size: 12px;
  color: #666;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.category-count {
  font-size: 12px;
  color: #409eff;
  font-weight: 500;
}

/* 过滤区域 */
.filter-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.filter-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

/* 主内容区域 */
.main-content {
  width: 100%;
}

.panel-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 网格视图 */
.document-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.document-card {
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 12px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.document-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  border-color: #409eff;
}

.document-icon {
  text-align: center;
  margin-bottom: 16px;
}

.document-icon .el-icon {
  font-size: 48px;
  color: #409eff;
}

.document-info {
  text-align: center;
}

.document-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #2c3e50;
}

.document-desc {
  font-size: 14px;
  color: #6c757d;
  margin: 0 0 12px 0;
  line-height: 1.4;
}

.document-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.document-category {
  background: #e3f2fd;
  color: #1976d2;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.document-size {
  color: #6c757d;
  font-size: 12px;
}

.document-actions {
  display: flex;
  gap: 8px;
  justify-content: center;
}

/* 列表视图 */
.document-list {
  width: 100%;
}

.document-name-cell {
  display: flex;
  align-items: center;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 18px;
  color: #6c757d;
  margin-bottom: 24px;
}

/* 预览对话框 */
.preview-content {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.file-preview {
  text-align: center;
}

.preview-icon {
  margin-bottom: 16px;
}

.preview-text {
  font-size: 16px;
  color: #6c757d;
  margin-bottom: 24px;
}

.image-preview {
  text-align: center;
}

/* 网盘链接预览样式 */
.link-preview {
  text-align: center;
  padding: 20px;
}

.link-info {
  max-width: 500px;
  margin: 0 auto;
}

.link-info h3 {
  color: #2c3e50;
  margin-bottom: 16px;
  font-size: 20px;
}

.link-url {
  background: #f5f7fa;
  padding: 12px;
  border-radius: 6px;
  margin: 16px 0;
  word-break: break-all;
  font-family: monospace;
  font-size: 14px;
  color: #606266;
  border: 1px solid #e4e7ed;
}

.extract-code {
  background: #fff3cd;
  padding: 12px;
  border-radius: 6px;
  margin: 12px 0;
  border: 1px solid #ffeaa7;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  color: #856404;
}

.extract-code .code {
  font-family: monospace;
  font-weight: bold;
  font-size: 16px;
  color: #e74c3c;
  margin: 0 8px;
}

.link-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin: 20px 0;
}

.preview-options {
  margin: 20px 0;
  padding: 16px;
  background: #f0f9ff;
  border-radius: 8px;
  border: 1px solid #b3d8ff;
}

.preview-options h4 {
  margin: 0 0 12px 0;
  color: #409eff;
  font-size: 16px;
}

.preview-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  flex-wrap: wrap;
}

.link-tips {
  text-align: left;
  background: #f0f9ff;
  padding: 16px;
  border-radius: 8px;
  border-left: 4px solid #409eff;
  margin-top: 20px;
}

.link-tips p {
  margin: 0 0 8px 0;
  font-weight: 600;
  color: #409eff;
}

.link-tips ul {
  margin: 0;
  padding-left: 20px;
}

.link-tips li {
  margin: 4px 0;
  color: #606266;
  line-height: 1.5;
}

/* 上传区域样式 */
.upload-section {
  position: relative;
}

.upload-divider {
  text-align: center;
  margin: 16px 0;
  position: relative;
}

.upload-divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #e4e7ed;
}

.upload-divider span {
  background: white;
  padding: 0 16px;
  color: #909399;
  font-size: 14px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .document-manage-container {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
    padding: 16px;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .page-subtitle {
    font-size: 14px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: center;
    gap: 8px;
    flex-wrap: wrap;
  }
  
  .filter-section {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .category-grid {
    grid-template-columns: 1fr;
  }
  
  .category-card {
    padding: 12px;
  }
  
  .category-icon {
    width: 40px;
    height: 40px;
  }
  
  .category-icon .el-icon {
    font-size: 20px;
  }
  
  .filter-left {
    flex-direction: column;
    gap: 12px;
  }
  
  .filter-left .el-input {
    width: 100% !important;
    margin-left: 0 !important;
  }
  
  .document-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .document-card {
    padding: 16px;
  }
  
  .document-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .document-actions .el-button {
    width: 100%;
  }
}
</style> 